const http = require('../../utils/http.js')
const userStepDataModel = require('../../model/userStepData.js');
const { STORAGE_KEY_TOKEN, STORAGE_KEY_USER_CODE, STORAGE_KEY_USER_NAME, STORAGE_KEY_USER_STEP_DATA_MODEL } = require('../../constant/storage_keys.js');
const { isLoggedIn, autoLogin, recordStepSyncTime } = require('../../utils/auth.js');

Page({
  data: {
    userCode: '111',
    name: 'whb',
    agreedToTerms: true, // 默认选中用户条款
    isAutoLogging: false // 是否正在自动登录
  },

  onLoad() {
    console.log('登录页面加载');
    // 如果用户已登录，尝试自动登录
    if (isLoggedIn()) {
      console.log('检测到用户已登录，尝试自动登录');
      this.performAutoLogin();
    }
  },

  /**
   * 执行自动登录
   */
  performAutoLogin() {
    this.setData({ isAutoLogging: true });

    autoLogin().then((userInfo) => {
      console.log('自动登录成功，用户信息:', userInfo);
      this.setData({ isAutoLogging: false });

      // 自动登录成功，跳转到首页
      wx.switchTab({
        url: '/pages/index/index',
        success: () => {
          console.log('自动登录后跳转首页成功');
        },
        fail: (err) => {
          console.error('自动登录后跳转首页失败:', err);
          wx.showToast({ title: '跳转首页失败', icon: 'none' });
        }
      });
    }).catch((error) => {
      console.error('自动登录失败:', error);
      this.setData({ isAutoLogging: false });
      // 自动登录失败，清除登录信息，用户需要手动登录
      wx.showToast({ title: '自动登录失败，请重新登录', icon: 'none' });
    });
  },

  onCodeInput(e) {
    this.setData({ userCode: e.detail.value });
  },

  onNameInput(e) {
    this.setData({ name: e.detail.value });
  },

  toggleTerms() {
    this.setData({ agreedToTerms: !this.data.agreedToTerms });
  },

  handleLogin() {
    // 如果正在自动登录，不允许手动登录
    if (this.data.isAutoLogging) {
      wx.showToast({ title: '正在自动登录中，请稍候', icon: 'none' });
      return;
    }

    console.log('handleLogin start:', this.data);
    if (!this.data.name) {
      wx.showToast({ title: '请输入姓名', icon: 'none' });
      return;
    }
    if (!this.data.userCode) {
      wx.showToast({ title: '请输入工号', icon: 'none' });
      return;
    }
    if (!this.data.agreedToTerms) {
      wx.showToast({ title: '请先同意服务条款', icon: 'none' });
      return;
    }
    wx.request({
      url: http.baseURL + '/api/user/login',
      method: 'POST',
      data: {
        name: this.data.name,
        userCode: this.data.userCode
      },
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        const code = res.data.code;
        console.log(`buryool:${JSON.stringify(res.data)}`)
        const msg = res.data.msg || (code === 200 ? '校验成功' : '校验失败');
        if (code === 200 && res.data.data && res.data.data.token) {
          const token = res.data.data.token;
          try {
            console.log('token:',token);
            wx.setStorageSync(STORAGE_KEY_TOKEN, token);
            // 保存用户姓名
            wx.setStorageSync(STORAGE_KEY_USER_NAME, this.data.name);
          } catch (e) { console.error('setToken error:', e); }
          this.doWxLoginAndGetSessionId();
        } else {
          wx.showToast({ title: msg, icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('login fail:', err);
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  doWxLoginAndGetSessionId() {
    console.log('doWxLoginAndGetSessionId start');
    wx.login({
      success: (loginRes) => {
        console.log('wx.login result:', loginRes);
        if (loginRes.code) {
          wx.request({
            url: http.baseURL + '/api/user/getSessionId',
            method: 'GET',
            data: {
              code: loginRes.code,
              userCode: this.data.userCode
            },
            header: {
              'content-type': 'application/json',
              'Authorization': 'Bearer ' + (typeof uni !== 'undefined' && uni.getStorageSync ? uni.getStorageSync(STORAGE_KEY_TOKEN) : wx.getStorageSync(STORAGE_KEY_TOKEN))
            },
            success: (res) => {
              console.log('getSessionId result:', res.data);
              const code = res.data.code;
              const msg = res.data.msg;
              if (code === 200 && res.data.data && res.data.data.sessionId) {
                this.checkOpenId(this.data.userCode, this.data.name, res.data.data.sessionId)
                wx.showToast({ title: msg, icon: 'success' });
              } else {
                wx.showToast({ title: msg, icon: 'none' });
              }
            },
            fail: (err) => {
              console.error('getSessionId fail:', err);
              wx.showToast({ title: '网络错误', icon: 'none' });
            }
          });
        } else {
          wx.showToast({ title: '获取微信code失败', icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('wx.login fail:', err);
        wx.showToast({ title: '微信登录失败', icon: 'none' });
      }
    });
  },

  // 服务器返回的code 用户name
  checkOpenId(code, name, sessionId) {
    console.log('checkOpenId start, code-name-sessionId', code + '-' + name + '-' + sessionId);
    wx.request({
      url: http.baseURL + '/api/user/checkOpenId',
      method: 'GET',
      data: {
        code: code,
        name: name,
        uuid: sessionId
      },
      header: {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + wx.getStorageSync(STORAGE_KEY_TOKEN)
      },
      success: (res) => {
        console.log('checkOpenId result:', res.data);
        const code = res.data.code;
        const msg = res.data.msg
        if (code === 200) {
          this.getWeRunAndStep(sessionId);
          wx.showToast({ title: msg, icon: 'success' });
        } else {
          wx.showToast({ title: msg, icon: 'none' });
        }
      },
      fail: (err) => {
        console.error('checkOpenId fail:', err);
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  getWeRunAndStep(sessionId) {
    console.log('getWeRunAndStep start, sessionId:', sessionId);
    wx.getWeRunData({
      success: (runRes) => {
        console.log('getWeRunData success:', runRes);
        const encryptedData = runRes.encryptedData;
        const iv = runRes.iv;
        wx.request({
          url: http.baseURL + '/api/wechat/steps/decodeWechatStep',
          method: 'POST',
          data: {
            sessionId: sessionId,
            encryptedData: encryptedData,
            userCode: this.data.userCode,
            iv: iv
          },
          header: {
            'content-type': 'application/json',
            'Authorization': 'Bearer ' + (typeof uni !== 'undefined' && uni.getStorageSync ? uni.getStorageSync(STORAGE_KEY_TOKEN) : wx.getStorageSync(STORAGE_KEY_TOKEN))
          },
          success: (res) => {
            console.log('decodeWechatStep result:', JSON.stringify(res.data));
            const code = res.data.code;
            if (code === 200) {
              wx.setStorageSync(STORAGE_KEY_USER_CODE, this.data.userCode);
              // 获取用户步数信息
              wx.request({
                url: http.baseURL + '/api/user/getUserStepInfo?userCode=' + wx.getStorageSync(STORAGE_KEY_USER_CODE),
                method: 'GET',
                header: {
                  'content-type': 'application/json',
                  'Authorization': 'Bearer ' + wx.getStorageSync(STORAGE_KEY_TOKEN)
                },
                              success: (res) => {
                if (res.data && res.data.code === 200) {
                  console.log('getUserStepInfo data:', res.data.data);
                  // 用Object.assign更新模型内容
                  Object.assign(userStepDataModel, res.data.data);
                  wx.setStorageSync(STORAGE_KEY_USER_STEP_DATA_MODEL, userStepDataModel);
                  // 记录步数同步时间
                  recordStepSyncTime();
                } else {
                  console.error('getUserStepInfo error:', res.data ? res.data.msg : '未知错误');
                }
              },
                fail: (err) => {
                  console.error('getUserStepInfo 网络错误:', err);
                }
              });
              setTimeout(() => {
                wx.switchTab({
                  url: '/pages/index/index',
                  success: () => { console.log('switchTab success'); },
                  fail: (err) => { console.error('switchTab fail:', err); wx.showToast({ title: '跳转首页失败', icon: 'none' }); }
                });
              }, 500);
            } else {
              wx.showToast({ title: msg, icon: 'none' });
            }
          },
          fail: (err) => {
            console.error('getWeRunAndStep fail:', err);
            wx.showToast({ title: '网络错误', icon: 'none' });
          }
        });
      },
      fail: (err) => {
        console.error('getWeRunData fail:', err);
        wx.showToast({ title: '获取微信运动数据失败', icon: 'none' });
      }
    });
  }
});
